<template>
    <div class="execution">
      <basic-container>
        <avue-form
          ref="form"
          v-model="form"
          :option="formOption"
          @submit="submit"
        >
           <!-- 办公地址 -->
           <template slot="detailAddress">
          <div class="detail-address-wrap" style="display: flex;">
            <el-input
              placeholder="具体地址"
              v-model="form.detailAddress"
              :disabled="true"
            ></el-input>
            <el-button
              icon="el-icon-location-information"
              @click="selectAddress"
              circle
             style="margin-left: 20px;"></el-button>
          </div>
        </template>
        <!-- 页面的上半部分在src\const\crud\public\team\index.js -->
        <template slot="billNo">
          <div>
            <el-input  v-model="form.billNo" :disabled="true"></el-input>
          </div>
        </template>
        <template slot="billDate">
                    <div class="block">
                      <el-date-picker
                        v-model="form.billDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="yyyy-MM-dd"
                        @change="inputNo(form)"
                        :disabled='isdisabled'
                      >
                      </el-date-picker>
                    </div>
        </template>
      
      <template slot="phone">
          <div>
            <el-input v-model="form.phone"   show-word-limit  
@keyup.native="UpNumber(form)"  @keydown.native="UpNumber(form)" clearable
            placeholder="请输入联系电话" >
            </el-input>
          </div>
        </template>
        <template slot="qr">
          <el-upload
            ref="upload"
            :action="upload.action"
            :headers="upload.headers"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-change="handleChangeUpload"
            :on-remove="handleRemove"
            list-type="picture-card"
            :multiple="false"
            :file-list="fileList"
            :data="params"
          >
            <div slot="tip" class="el-upload__tip">
              支持格式：建议上传(分辨率602*652)，仅能上传一张，请使用5M以下的jpg、jpeg、png的图片
            </div>
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
    
         

        </avue-form>
      </basic-container>
      <!-- 地图选点 -->
    <map-location ref="mapLocation" @changeSelect="handleSelectAddress" />
    </div>
  </template>
  
  <script>
 
  import { getObj, putObj, addObj } from '@/api/public/about'
  import { formOption } from '@/const/crud/public/about'
  import Upload from "@/components/upload/index";
  import tinymceEditor from "@/components/tinymce/index";
  import TerritoryCascade from "@/components/territory-cascade";
  import MapLocation from "@/components/tencent-map/dialog-map";
  export default {
    components: {
      Upload,
      MapLocation,
      tinymceEditor,
      TerritoryCascade,
    },
    data() {
      return {
       
        fileList: [],
        fileList2: [],
        upload: {
          action: `${process.env.VUE_APP_TARGET}/admin/sys-file/uploadPicture`,
          headers: {},
        },
        params: { platformId: 1 },
        form: {
          qr:"",
          id: null,    
          signUpDateBgn:"",
          signUpDateEnd:"",
        
          billDate:'',
          showOnIndex:0
        },
        formOption: formOption,
        territoryObj: {},
        isdisabled:false,
      };
    },
    mounted() {
      this.upload.headers = {
        Authorization: `Bearer ${this.$store.getters.access_token}`,
        "TENANT-ID": 1,
      };
      this.init();
    },
    created() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=DTFBZ-TDHCQ-SCJ5U-GS54L-SBRRZ-NCBPO";
      document.body.appendChild(script);
    },
    methods: {
        // 选取地址
    selectAddress() {
      this.$nextTick(() => {
        this.$refs.mapLocation.init();
      });
    },
      init() {
        let id = this.$route.query.id ? this.$route.query.id : -1;
        if (id !== -1) {
          this.isdisabled=true
          getObj(id).then(({ data }) => {
            if (data.code === 0) {
              let detail = data.data;
              this.form = detail
              if (this.form.qr) {
                this.fileList.push({ url: this.form.qr });
              }
            }
          });
        }
      },

      UpNumber(form) {
  this.form.phone = form.phone.slice(0, 11).replace(/[^\d]/g, '');
},
      inputNo(form){
   
        var postData = {
          billDate:form.billDate
        }
        if(form.billDate){
        getBillNo(postData).then(({ data }) => {
            this.form.billNo = data
        });
      }
      },

      // 提交表单
      submit(form, done) {
        let msg = ''
      if(form.linkMan == '' || !form.linkMan) {
        msg = msg.concat('联系人 ')
      }
      if(form.phone == '' || !form.phone) {
        msg = msg.concat('联系电话')
      }
      if(form.address == '' || !form.address) {
        msg = msg.concat('地址 ')
      }
      if(msg !== '' ) {
        done()
        return
      } 
      if(form.phone){
  const phoneRegex = /^1[3456789]\d{9}$/;

if (!phoneRegex.test(form.phone)) {
  this.$message.warning('请输入有效的手机号');
  done();
  return;
}
}

//          if ('isPublish' in form) {
//  if(form.isPublish===''){
//           form.isPublish=0
//         }
//       }
      if ('isCanceled' in form) {
 if(form.isCanceled===''){
          form.isCanceled=1
        }
      }  
        let arr = JSON.parse(JSON.stringify(form));    
        if (arr.id) {
          // 编辑serverType
          putObj(arr).then(({ data }) => {

            if (data.code === 0) {
              this.$message.success("编辑成功");
              done();
              setTimeout(() => {
                this.$router.push("/public/about/index");
              }, 1000);
            } else{
              this.$message.error("编辑失败");
              done();
              setTimeout(() => {
                this.$router.push("/public/about/index");
              }, 1000);
            }

          });
        } else {
          addObj(arr).then(({ data }) => {
            if (data.code === 0) {
              this.$message.success("新增成功");
              done();
              setTimeout(() => {
                this.$router.push("/public/about/index");
              }, 1000);
            }else{
              this.$message.error("新增失败");
              done();
              setTimeout(() => {
                this.$router.push("/public/about/index");
              }, 1000);
            }
          });
        }
      },
      // 清空
      empty() {
        this.$refs.form.resetForm();
      },
       // 获取选取的地址
    handleSelectAddress(data) {
      let locationArr = data.area_info.split(" ");
      this.form.provinceAddress = locationArr[0];
      this.form.cityAddress = locationArr[1];
      this.form.districtAddress = locationArr.length >= 3 ? locationArr[2] : "";
      this.form.latitude = data.address_latitude;
      this.form.longitude = data.address_longitude;
      // 具体地址
      this.form.detailAddress =
        this.form.provinceAddress +
        this.form.cityAddress +
        this.form.districtAddress +
        data.address_detail;
    },
      beforeAvatarUpload(file) {
        const is5M = file.size / 1024 / 1024 < 5;
        if (!is5M) {
          this.$message.error("大小不超过5M");
          return is5M;
        }
        const type = file.name
          .substring(file.name.lastIndexOf(".") + 1)
          .trim()
          .toLowerCase();
          const isType =
            type === "jpg" || type === "jpeg" || type === "png" || type === "gif";
          if (!isType) {
            this.$message.error("请使用jpg、jpeg、png的图片");
            return isType;
          }
      },
      handleChangeUpload(file, fileList) {
        if (fileList.length > 1) {
          this.fileList = [fileList[fileList.length - 1]];
          this.$nextTick(() => {
            // 主动去调用提交接口
            this.$refs.upload.submit();
          });
          // 若文件只有一个，直接上传
        }
      },
      handleRemove(file, fileList) {
        this.fileList = fileList;
        this.form.qr = "";
      },
      // 上传图片成功
      handleAvatarSuccess(res) {
        if (res.code == 0) {
          this.form.qr = res.data.url;
        } else {
          this.$message.warning(res.msg);
        }
      },
      handleChangeUpload2(file, fileList) {
        if (fileList.length > 1) {
          this.fileList2 = [fileList[fileList.length - 1]];
          this.$nextTick(() => {
            // 主动去调用提交接口
            this.$refs.upload.submit();
          });
          // 若文件只有一个，直接上传
        }
      },
      handleRemove2(file, fileList) {
        this.fileList2 = fileList;
        this.form.qr = "";
      },

      handleAvatarSuccess2(res) {
        if (res.code == 0) {
          this.form.qr = res.data.url;
        } else {
          this.$message.warning(res.msg);
        }
      },
    },
  };
  </script>
  